import { useUserStore, usePermissionStore } from '@/store'

/**
 * @description: 判断用户是否有权限
 * @param {*} permission
 * @return {*}
 */
function hasPermission(permission) {
  const userStore = useUserStore()
  const userPermissionStore = usePermissionStore()

  const accessApis = userPermissionStore.apis
  if (userStore.isSuperUser) {
    return true
  }
  return accessApis.includes(permission)
}

/**
 * @description: 权限指令 在指令的 mounted 和 beforeUpdate 钩子中调用 updateElVisible 函数，根据权限判断是否移除元素
 * @param {*} app
 * @return {*}
 */
export default function setupPermissionDirective(app) {
  function updateElVisible(el, permission) {
    if (!permission) {
      throw new Error(`need roles: like v-permission="get/api/v1/user/list"`)
    }
    if (!hasPermission(permission)) {
      el.parentElement?.removeChild(el)
    }
  }

  const permissionDirective = {
    mounted(el, binding) {
      updateElVisible(el, binding.value)
    },
    beforeUpdate(el, binding) {
      updateElVisible(el, binding.value)
    },
  }

  app.directive('permission', permissionDirective)
}
